package com.meitianhui.convenitenbuy.module.store.ui;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseFragment;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.main.model.bean.AppToken;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.mine.model.LogOutBean;
import com.meitianhui.convenitenbuy.module.store.adapter.StoreAdapter;
import com.meitianhui.convenitenbuy.module.store.contract.StoreContract;
import com.meitianhui.convenitenbuy.module.store.di.DaggerStoreComponent;
import com.meitianhui.convenitenbuy.module.store.di.StoreModule;
import com.meitianhui.convenitenbuy.module.store.model.StoreInfo;
import com.meitianhui.convenitenbuy.module.store.model.StoreType;
import com.meitianhui.convenitenbuy.module.store.presenter.StorePresenter;
import com.meitianhui.convenitenbuy.module.store.ui.activity.StoreDetailActivity;
import com.meitianhui.convenitenbuy.module.store.ui.activity.StoreMapActivity;
import com.meitianhui.convenitenbuy.module.store.ui.activity.StoreSearchActivity;
import com.meitianhui.convenitenbuy.util.LocationService;
import com.meitianhui.convenitenbuy.util.PreferenceUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2017/10/30.
 */

public class StoreFragment extends BaseFragment implements StoreContract.View,SwipeRefreshLayout.OnRefreshListener{
    public static final String Tag = StoreFragment.class.getSimpleName();
    private RecyclerView mRvStore;
    private SwipeRefreshLayout mSwipeLayout;
    private TextView mTvDistance,mTvType,mTvRecommend;
    private int mPageIndex = 1;
    private int mPageSize = 15;
    private StoreAdapter mAdapter;
    private View mNotDataView;
    private String mRange = "30000";
    private String mStoreType = "";
    private List<StoreType> mStoreTypeList;
    private List<StoreInfo.Convenient> mStoreInfoList;
    private TextView mTvContent;
    private String mNoContent;
    private View mViewFooter;
    private ImageView mIvPhone;

    @Inject
    StorePresenter presenter;
    private LocationService mLocationService;

    @Override
    protected int getLayout() {
        return R.layout.fragment_store;
    }


    @Override
    protected void initView(LayoutInflater inflater) {
        super.initView(inflater);
        DaggerStoreComponent
                .builder()
                .appComponent(App.getInstance().getAppComponent())
                .storeModule(new StoreModule(this))
                .build()
                .inject(this);
        initView();
        initData();
    }
    private void initView(){
        mSwipeLayout = (SwipeRefreshLayout) getViewById(R.id.swipe_layout);
        mSwipeLayout.setOnRefreshListener(this);
        mRvStore = (RecyclerView) getViewById(R.id.rv_store);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRvStore.setLayoutManager(layoutManager);
        mNotDataView = getActivity().getLayoutInflater().inflate(R.layout.data_empty_goods, (ViewGroup) mRvStore.getParent(), false);
        mViewFooter = getActivity().getLayoutInflater().inflate(R.layout.item_store_footer, (ViewGroup) mRvStore.getParent(), false);
        mTvContent = (TextView) mNotDataView.findViewById(R.id.tv_content);
        RxUtils.bindEvents(getViewById(R.id.iv_radar),this);
        RxUtils.bindEvents(getViewById(R.id.ll_search),this);
        mTvDistance = (TextView) getViewById(R.id.tv_distance);
        RxUtils.bindEvents(mTvDistance,this);
        mTvType = (TextView) getViewById(R.id.tv_type);
        RxUtils.bindEvents(mTvType,this);
        mTvRecommend = (TextView) getViewById(R.id.tv_recommend);
        RxUtils.bindEvents(mTvRecommend,this);
        mIvPhone = (ImageView) getViewById(R.id.iv_phone);
        getData();
        registerPush();
    }


    private void getData(){
        //状态栏的设置
        RelativeLayout storeSearch = (RelativeLayout)getViewById(R.id.store_search);
        int systemBarHeight = SystemUtils.getSystemBarHeight(App.getInstance());
        storeSearch.setPadding(storeSearch.getPaddingLeft(),systemBarHeight,storeSearch.getPaddingRight(),storeSearch.getPaddingBottom());
        storeSearch.getLayoutParams().height = systemBarHeight+ (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,59,App.getInstance().getResources().getDisplayMetrics());
        if(TextUtils.isEmpty(InfoProvider.getAppToken(App.getInstance()))){
            presenter.getAppToken();
        }else{
            presenter.getStoreType();
        }
    }
    private void registerPush() {
        Disposable subscribe = RxBus.get().toFlowable(EventBean.class).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean bean) throws Exception {
                if (bean != null) {
                    if (bean.type == Constants.EVENT_TYPE_LOGIN_SUCCESS) {
                        getData();
                        presenter.getStoreList(InfoProvider.getLongitude(getActivity()), InfoProvider.getLatitude(getActivity()), mRange, mStoreType, mPageIndex + "", mPageSize + "");
                    }
                }
            }
        });
        Disposable logout = RxBus.get().toFlowable(LogOutBean.class).subscribe(new Consumer<LogOutBean>() {
            @Override
            public void accept(LogOutBean logOutBean) throws Exception {
                if (logOutBean.logOut.equals("logout")) {
                    getData();
                    presenter.getStoreList(InfoProvider.getLongitude(getActivity()), InfoProvider.getLatitude(getActivity()), mRange, mStoreType, mPageIndex + "", mPageSize + "");
                }
            }
        });


        mCompositeDisposable.add(subscribe);
        mCompositeDisposable.add(logout);

    }

    private void initData(){
        mAdapter = new StoreAdapter(getActivity(),null,null);
        mRvStore.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getActivity(), StoreDetailActivity.class);
                intent.putExtra("store_id",mStoreInfoList.get(position).getStores_id());
                intent.putExtra("store_name",mStoreInfoList.get(position).getStores_name());
                intent.putExtra("store_address",mStoreInfoList.get(position).getAddress());
                startActivity(intent);
            }
        });
        presenter.getStoreList(InfoProvider.getLongitude(getActivity()),InfoProvider.getLatitude(getActivity()),mRange,mStoreType,mPageIndex+"",mPageSize+"");
        //重新定位 获取经纬度
        mLocationService = new LocationService(App.getInstance());
        mLocationService.registerListener(mLocationListener);
        mLocationService.start();
    }
        private BDLocationListener mLocationListener = new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                mLocationService.stop();
                if (location !=null && location.getLocType() != BDLocation.TypeServerError
                        && !(location.getLatitude() + "").equals("4.9E-324") && !(location.getLatitude() + "").equals("4.9E-324")){
                    //保存经纬度
                    PreferenceUtils.putString(getActivity(), Constants.LONGITUDE, location.getLongitude() + "");
                    PreferenceUtils.putString(getActivity(), Constants.LATITUDE, location.getLatitude() + "");
                    PreferenceUtils.putString(getActivity(), Constants.CITY, location.getCity() + "");
                    PreferenceUtils.putString(getActivity(), Constants.DISTRICT, location.getDistrict() + "");
                }
            }
        };

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()){
            case R.id.iv_radar:    //雷达
                if ( mStoreInfoList == null && TextUtils.isEmpty(InfoProvider.getLatitude(getActivity()))) {
                    TipUtils.showToast(App.getInstance(),"正在获取当前位置",2);
                    return;
                }
                Intent intent = new Intent(getActivity(), StoreMapActivity.class);
                intent.putExtra("list", (Serializable) mStoreInfoList);
                startActivity(intent);

                break;
            case R.id.ll_search:  //搜索

                startActivity(new Intent(getActivity(),StoreSearchActivity.class));
                break;
            case R.id.tv_distance:   //距离
                presenter.setOnDistance();
                break;
            case R.id.tv_type:  //类别

                if(mStoreTypeList==null){
                    presenter.getStoreType();
                }else{
                    presenter.setOnType(mStoreTypeList);
                }

                break;
            case R.id.tv_recommend:  //推荐
                presenter.setOnRecommend();
                break;

        }
    }

    @Override
    public void onRefresh() {
        mPageIndex = 1;
        if (TextUtils.isEmpty(InfoProvider.getAppToken(getActivity()))) {
            presenter.getAppToken();
        } else {
            presenter.getStoreList(InfoProvider.getLongitude(getActivity()),InfoProvider.getLatitude(getActivity()),mRange,mStoreType,mPageIndex+"",mPageSize+"");
        }
    }

    @Override
    public void getAppTokenSuccess(AppToken appToken) {
        PreferenceUtils.putString(getActivity(), Constants.APP_TOKEN_KEY,appToken.getApp_token());
        PreferenceUtils.putString(getActivity(), Constants.APP_SECURITY_CODE,appToken.getSecurity_code());
        presenter.getStoreType();
    }

    @Override
    public void getStoreListSuccess(StoreInfo data) {
        mSwipeLayout.setRefreshing(false);
        setData(mPageIndex,data.getList(),data.getDoc_url());
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPageIndex++;
                presenter.getStoreList(InfoProvider.getLongitude(getActivity()),InfoProvider.getLatitude(getActivity()),mRange,mStoreType,mPageIndex+"",mPageSize+"");
            }
        },mRvStore);
    }

    @Override
    public void getStoreListFail(int code, String msg) {
        mSwipeLayout.setRefreshing(false);
        mAdapter.setEmptyView(mNotDataView);
    }

    @Override
    public void getStoreTypeSuccess(List<StoreType> data) {
        mStoreTypeList = data;
        StoreType storeType = new StoreType();
        storeType.setIndex("000");
        storeType.setContent("全部");
        mStoreTypeList.set(0,storeType);
    }

    @Override
    public void getDistance(String id, String content) {
        mTvDistance.setText(content);
        if(!content.equals("全城")){
            mNoContent = content.replace("<","");
            mTvContent.setText("附近"+mNoContent+"未找到相关商家服务");
        }else{
            mTvContent.setText("全城皆未找到相关商家服务");
        }
        mRange = id;
        onRefresh();
    }

    @Override
    public void getType(String id, String content) {
        if(id.equals("000")){
            mStoreType = "";
        }else{
            mStoreType = id;
        }
        mTvType.setText(content);
        onRefresh();
    }

    @Override
    public void getRecommend(String id, String content) {
        mTvRecommend.setText(content);
    }

    @Override
    public void onFail(int code, String msg) {
        mSwipeLayout.setRefreshing(false);
    }

    private void setData(int pageIndex, List data, Map<String, String> map) {
        final int size = data == null ? 0 : data.size();
        mAdapter.removeAllFooterView();
        if(pageIndex==1){
            mAdapter.setNewData(data,map);
            if(size==0){
                mAdapter.setEmptyView(mNotDataView);
                mAdapter.addFooterView(mViewFooter);
            }
            if(size==0||size==1){
                mIvPhone.setVisibility(View.VISIBLE);
            }else{
                mIvPhone.setVisibility(View.GONE);
                mAdapter.addFooterView(mViewFooter);
            }
        }else{
            mIvPhone.setVisibility(View.GONE);
            mAdapter.addFooterView(mViewFooter);
            if(size>0){
                mAdapter.addData(data,map);
            }
        }
        mStoreInfoList = mAdapter.getData();
        if (size < mPageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(false);
        } else {
            mAdapter.loadMoreComplete();
        }
    }
    @Override
    public void showError(String msg) {

    }
}
